import env from '@/utils/env';

function service(options = {}) {
	options.url = `${env.baseUrl}${options.url}`;
	// 判断本地是否存在token，如果存在则带上请求头
	let token = uni.getStorageSync('token')
	// console.log("token",token);
	options.header = {
		'Authorization': `Bearer ${token || false}` // 这里是token(可自行修改)
	};
	// resolved是返回成功数据，rejected返回错误数据
	return new Promise((resolved, rejected) => {
		options.success = (res) => {
			// token过期
			if (res.statusCode == 401) {
				uni.login({
					provider: 'weixin',
					success: (res) => {
						uni.request({
							url: 'https://wechat.atptest.com:44386/connect/token',
							data: {
								code: res.code,
								grant_type: 'wechat'
							},
							method: 'POST',
							header: {
								'content-type': 'application/x-www-form-urlencoded',
								'Authorization': 'Basic QXBpX1dlYjpBcGlfV2Vi'
							},
							success(res1) {
								uni.setStorageSync('token', res1.data.access_token)
								// console.log('options',options);
								options.header = {
									'Authorization': `Bearer ${res1.data.access_token || false}` // 这里是token(可自行修改)
								};
								return uni.request(options);
							},
							fail(err) {
								console.log("请求token失败", err);
							}
						})
					}
				})
			} else if (res.statusCode == 200) {
				// 请求回来的状态码为200则返回内容
				if (res.data.code == 400) {
					if (res.data.message == '无效Code。') {
						uni.showToast({
							duration: 5000,
							title: '优惠券已被领取',
							icon: 'none'
						})
					} else {
						uni.showToast({
							duration: 2000,
							title: res.data.message,
							icon: 'none'
						})
					}
					resolved(res.data)
				}
				resolved(res.data.data)
			} else {
				uni.showToast({
					duration: 5000,
					title: '接口异常',
					icon: 'none'
				})
				rejected(res);
			}
		};

		options.fail = (err) => {
			// 请求失败弹窗
			uni.showToast({
				duration: 5000,
				title: err
			});
			rejected(err);
		};

		uni.request(options);
	});
}

export default service;